(function (G) {
    const recorderManager = wx.getRecorderManager()
    const innerAudioContext = wx.createInnerAudioContext()
    const aiUrl = G.Storage.get('AIURL')
    G.vue({
        data: {
            actionFiles:[],
            APIURL: G.Storage.get('APIURL'),
            actionDescription: '',
            firstTypeList: ['吵架', '打架'], // 大类列表
            index: 0, // 第几个大类
            actionType:1,//上报种类
            location:[],//经纬度
            affiliatedAcompany:'',//所属公司
            address:'',//详细地址
            tempFilePath:''//存放音频
        },
        methods: {
            // 获取输入内容
            bindinput(e) {
                this.setData({
                    actionDescription: e.detail.value
                })
            },
             // 选择大类
            selectFirstType(e) {
                this.setData({
                index: e.detail.value,
                actionType: parseInt(e.detail.value) + 1
                })
            },
            
            selectLocation() {
                let that = this
                wx.getLocation({
                    type: 'wgs84',
                    success(res) {
                        const latitude = res.latitude
                        const longitude = res.longitude
                        let loca =JSON.stringify([[longitude,latitude]])
                        that.setData({
                            location:loca
                        })
                        //获取地址
                        G.get('/v1/map/geocodeRegeo',{longitude:longitude,latitude:latitude}).then(res=>{
                            that.setData({
                                address:res.regeocode.formatted_address
                            })
                        })
                    }
                })

            },
            // 获取所属公司
            getCompany(){
                let  id = G.Storage.get('userInfo').unitId
                let that = this
                G.get('/api/model/unit',{unitId:id}).then(res=>{
                    that.setData({
                        affiliatedAcompany:res[0].name
                    })
                })
            },
            // 删除图片
            delPic(e) {
                const {
                    index
                } = e.currentTarget.dataset

                let uploadList = [...this.data.actionFiles]
                uploadList.splice(index, 1)

                this.setData({
                    actionFiles: uploadList
                })

            },
            upload(e) {
                const {
                    type
                } = e.currentTarget.dataset
                let _self = this;

                if (this.data.actionFiles.length >= 5) return wx.showToast({
                    title: '最多上传5张',
                    icon: 'none'
                })
                wx.chooseMedia({
                    count: 5,
                    mediaType: ['image'],
                    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album'], //从相册选择
                    success(res) {
                        console.log(res, '选择图片')
                        const tempFilePaths = res.tempFiles;
                        for (var k in tempFilePaths) {
                            _self.uploadRequest(tempFilePaths[k].tempFilePath)
                        }
                    },
                    error: function (e) {
                        console.log(e);
                    }
                });

            },
            //图片
            uploadRequest(img) {
                let _self = this;
                if (this.data.actionFiles.length >=2) return wx.showToast({
                    title: '最多上传2张',
                    icon: 'none'
                })
                wx.showLoading({
                    title: '上传中...',
                })
                const uploadTask = wx.uploadFile({
                    url: G.Storage.get('APIURL') + '/upload',
                    filePath: img,
                    name: 'file',
                    header: {
                        'token': G.Storage.get('userInfo').token
                    },
                    success(rej) {
                        try {
                            let showUrl = JSON.parse(rej.data).id
                            let url = G.Storage.get('APIURL') + '/file/' + showUrl
                            console.log(url, 'url')
                            let uploadList = [..._self.data.actionFiles, {
                                url,
                                showUrl
                            }]
                            console.log(uploadList, 'uploadList')
                            _self.setData({
                                actionFiles: uploadList
                            })
                            wx.hideLoading()
                        } catch (e) {
                            //TODO handle the exception
                        }
                    },
                    fail(err) {
                        console.log(err)
                    }
                });
            },
            submit() {
                if (this.data.actionDescription == '') {
                    wx.showToast({
                        title: '请输入描述',
                        icon:'none'
                    })
                    return
                } else if (this.data.actionFiles.length == 0) {
                    wx.showToast({
                        title: '请上传图片',
                        icon:'none'
                    })
                    return
                } else {
                    let actionFiles = this.data.actionFiles.map(item => item.url)
                    const params = {
                        actionDescription:this.data.actionDescription,
                        actionFiles,
                        actionType:this.data.actionType,
                        affiliatedAcompany:this.data.affiliatedAcompany,
                        location:this.data.location,
                        status:2,
                        address:this.data.address,
                        userId: G.Storage.get('userInfo').userId
                    }
                    console.log('params',params)
                    G.post('/api/model/warning_system',params).then(res=>{
                        if(!res.errorMsg){
                            G.toask('上报成功')
                            this.$back()
                        }else{
                            G.toask('上报失败')
                        } 
                    })
                }
            },
            touchStart: function (e) {  //记录触屏开始时间
                // this.setData({start:e.timeStamp })
                console.log('长按开始事件')
                var that=this
                const options = {
                    duration: 10000,//指定录音的时长，单位 ms
                    sampleRate: 16000,//采样率
                    numberOfChannels: 1,//录音通道数
                    encodeBitRate: 96000,//编码码率
                    format: 'wav',//音频格式，有效值 aac/mp3
                    frameSize: 50,//指定帧大小，单位 KB
                }
                //开始录音
                wx.authorize({
                scope: 'scope.record',
                success() {
                    console.log("录音授权成功");
                    //第一次成功授权后 状态切换为2
                    that.setData({
                    status: 2,
                    })
                    recorderManager.start(options);
                    recorderManager.onStart(() => {
                    console.log('recorder start')
                    });
                    //错误回调
                    recorderManager.onError((res) => {
                    console.log(res);
                    })
                },
                fail() {
                    console.log("第一次录音授权失败");
                    wx.showModal({
                    title: '提示',
                    content: '您未授权录音，功能将无法使用',
                    showCancel: true,
                    confirmText: "授权",
                    confirmColor: "#52a2d8",
                    success: function (res) {
                        if (res.confirm) {
                        //确认则打开设置页面（重点）
                        wx.openSetting({
                            success: (res) => {
                            console.log(res.authSetting);
                            if (!res.authSetting['scope.record']) {
                                //未设置录音授权
                                console.log("未设置录音授权");
                                wx.showModal({
                                title: '提示',
                                content: '您未授权录音，功能将无法使用',
                                showCancel: false,
                                success: function (res) {

                                },
                                })
                            } else {
                                //第二次才成功授权
                                console.log("设置录音授权成功");
                                that.setData({
                                status: 2,
                                })
                        
                                recorderManager.start(options);
                                recorderManager.onStart(() => {
                                 console.log('recorder start')
                                });
                                //错误回调
                                recorderManager.onError((res) => {
                                console.log(res);
                                })
                            }
                            },
                            fail: function () {
                            console.log("授权设置录音失败");
                            }
                        })
                        } else if (res.cancel) {
                        console.log("cancel");
                        }
                    },
                    fail: function () {
                        console.log("openfail");
                    }
                    })
                }
                })
            },
            touchEnd: function (e) {  //记录触屏结束时间
                recorderManager.stop();
                recorderManager.onStop((res) => {
                    this.tempFilePath = res.tempFilePath;
                    console.log('停止录音', res.tempFilePath)
                    wx.uploadFile({
                      filePath: res.tempFilePath,
                      name: 'file',
                      url:aiUrl + '/voice_upload/upload',
                      formData:{
                          file:res.tempFilePath
                      },
                      header:{
                        "Content-Type": "multipart/form-data",
                        'token': G.Storage.get('userInfo').token,
                      },
                      success(re){
                          
                        console.log('返回数据',JSON.parse(re.data))
                      }
                    })
                })   
            },
            //播放声音
            play: function () {
                innerAudioContext.autoplay = true
                innerAudioContext.src = this.tempFilePath,
                innerAudioContext.onPlay(() => {
                    console.log('开始播放')
                })
                innerAudioContext.onError((res) => {
                console.log(res.errMsg)
                console.log(res.errCode)
                })
            }, 
        },
        created(){
            this.selectLocation()
            this.getCompany()
        }
    })
})(wx.$)